<template>
  <!-- 采购协议表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="45%"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12"
          ><el-form-item label="采购协议号" prop="purchasePlanNumber">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.purchasePlanNumber"
              placeholder="请输入"
              style="width: 192px"
              clearable
            />

            <span v-else>{{ formData.purchasePlanNumber }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" required>
            <el-select
              v-if="!props.isReadonly"
              @change="partnerChange"
              v-model="formData.partnerId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in partners"
                :key="item.id"
                :label="item.partnerName"
                :value="item.id"
              />
            </el-select>
            <span v-else
              >{{ formData.partnerName }}({{ formData.partnerCode }})</span
            >
          </el-form-item></el-col
        >
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="工厂" required>
            <el-select
              v-if="!props.isReadonly"
              @change="plantChange"
              v-model="formData.plantId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in plants"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              />
            </el-select>
            <span v-else
              >{{ formData.plantName }} ({{ formData.plantCode }})</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料" required>
            <el-select
              v-if="!props.isReadonly"
              @change="materialChange"
              v-model="formData.materialId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in materials"
                :key="item.id"
                :label="item.materialName"
                :value="item.id"
              />
            </el-select>
            <span v-else
              >{{ formData.materialName }}({{ formData.materialNumber }})</span
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="生效日期" prop="beginDate">
            <template v-if="!props.isReadonly">
              <el-date-picker
                v-model="formData.beginDate"
                type="date"
                placeholder="请选择生效日期"
                style="width: 192px"
                clearable
              />
            </template>
            <template v-else>
              <span>{{ formData.beginDate }}</span>
            </template>
          </el-form-item></el-col
        >
        <el-col :span="12">
          <el-form-item label="截止日期" prop="endDate">
            <template v-if="!props.isReadonly">
              <el-date-picker
                v-model="formData.endDate"
                type="date"
                placeholder="请选择截止日期"
                style="width: 192px"
                clearable
              />
            </template>
            <template v-else>
              <span>{{ formData.endDate }}</span>
            </template>
          </el-form-item></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="最大采购量" prop="maxPlanQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.maxPlanQuantity"
              placeholder="请输入"
              style="width: 192px"
              clearable
            >
              <template #append>个</template>
            </el-input>
            <span v-else>{{ formData.maxPlanQuantity }} </span>
          </el-form-item></el-col
        >
        <el-col :span="12">
          <el-form-item label="最小采购批量" prop="minBatchQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.minBatchQuantity"
              placeholder="请输入"
              style="width: 192px"
              clearable
            >
              <template #append>个</template>
            </el-input>
            <span v-else>{{ formData.minBatchQuantity }}</span>
          </el-form-item></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="默认采购价格" prop="normalPrice">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.normalPrice"
              placeholder="请输入"
              style="width: 192px"
              clearable
            >
              <template #append>元</template>
            </el-input>
            <span v-else>{{ formData.normalPrice }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="当期采购价格" prop="currentPrice">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.currentPrice"
              placeholder="请输入"
              style="width: 192px"
              clearable
            >
              <template #append>元</template>
            </el-input>
            <span v-else>{{ formData.currentPrice }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="执行税率" prop="taxRate">
        <el-input
          v-if="!props.isReadonly"
          v-model="formData.taxRate"
          placeholder="请输入"
          style="width: 192px"
          clearable
        />

        <span v-else>{{ formData.taxRate }}</span>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMSRMPURCHASEPLANADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

let plants = ref([]);
let materials = ref([]);
let partners = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    plants.value = [];
    getPartners();
  }
);

const rules = reactive({
  partnerCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialNumber: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  purchasePlanNumber: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  beginDate: [],
  endDate: [],
  maxPlanQuantity: [],
  normalPrice: [],
  currentPrice: [],
  taxRate: [],
  minBatchQuantity: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  organizationId: "ddf3c7ec594d4421ad82ce2d99fc3f58",
  organizationCode: "100",
  organizationName: "大连创新零部件",
  plantId: "",
  plantCode: "",
  plantName: "",
  materialId: "",
  materialNumber: "",
  materialName: "",
  purchasePlanNumber: "",
  beginDate: "",
  endDate: "",
  maxPlanQuantity: "",
  normalPrice: "",
  currentPrice: "",
  taxRate: "",
  minBatchQuantity: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";

    if (newVal?.id) {
      const {
        id,
        partnerId,
        partnerCode,
        partnerName,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        materialId,
        materialNumber,
        materialName,
        purchasePlanNumber,
        beginDate,
        endDate,
        maxPlanQuantity,
        normalPrice,
        currentPrice,
        taxRate,
        minBatchQuantity,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        partnerId,
        partnerCode,
        partnerName,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        materialId,
        materialNumber,
        materialName,
        purchasePlanNumber,
        beginDate,
        endDate,
        maxPlanQuantity,
        normalPrice,
        currentPrice,
        taxRate,
        minBatchQuantity,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
      });
      //获取物料等信息

      getPartners();
      getPlants();
      getMaterials();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.materialId = "";
  formData.materialNumber = "";
  formData.materialName = "";
  formData.purchasePlanNumber = "";
  formData.beginDate = "";
  formData.endDate = "";
  formData.maxPlanQuantity = "";
  formData.normalPrice = "";
  formData.currentPrice = "";
  formData.taxRate = "";
  formData.minBatchQuantity = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.deleted = "";
  materials.value = [];
}

const loading = ref(false);

async function getPlants() {
  const data = await request({
    url: "/srm/core/common/getPartnerPlantList",
    method: "get",
    params: { partnerId: formData.partnerId },
  });
  plants.value = data.data;
  console.log(plants);
}
async function getPartners() {
  const data = await request({
    url: "/srm/core/mdmpartner/getList",
    method: "post",
    data: {},
  });
  partners.value = data.data;
}
async function getMaterials() {
  const data = await request({
    url: `/srm/core/material/getListForRoughcast`,
    method: "post",
    data: {
      plantId: formData.plantId,
    },
  }).finally(() => {
    loading.value = false;
  });
  materials.value = data.data;
  console.log(materials);
}
function plantChange() {
  var plant = plants.value.find((item) => {
    return item.key === formData.plantId;
  });
  formData.plantCode = plant.code;
  formData.plantName = plant.label;
  formData.materialId = "";
  formData.materialNumber = "";
  formData.materialName = "";
  getMaterials();
}
function partnerChange() {
  var partner = partners.value.find((item) => {
    return item.id === formData.partnerId;
  });
  formData.partnerCode = partner.partnerCode;
  formData.partnerName = partner.partnerName;
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.materialId = "";
  formData.materialNumber = "";
  formData.materialName = "";
  getPlants();
}
function materialChange() {
  var material = materials.value.find((item) => {
    return item.id === formData.materialId;
  });
  formData.materialNumber = material.materialCode;
  formData.materialName = material.materialName;
}
/** 采购协议保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (formData.beginDate >= formData.endDate) {
        ElMessage.error("生效日期不能大于等于截止日期");
        return; // 返回以阻止继续执行保存操作
      }
      if (formData.minBatchQuantity > formData.maxPlanQuantity) {
        ElMessage.error("最小采购批量不能大于最大采购量");
        return; // 返回以阻止继续执行保存操作
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";

      await request({
        url: "/srm/core/srmpurchaseplan/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
